/**
 * @description: 导出文件流
 * @param {*} res  所有文件参数
 * @return {*}
 */
export function resolveBlob(res) {
  const aLink = document.createElement("a");
  var blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
  //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*");
  console.log(patt);
  var contentDisposition = decodeURI(res.headers["content-disposition"]);
  var result = patt.exec(contentDisposition);
  console.log(result);
  var fileName = result[1];
  fileName = fileName.replace(/\"/g, "");
  console.log(fileName);
  aLink.style.display = "none";
  aLink.href = URL.createObjectURL(blob);
  aLink.setAttribute("download", fileName); // 设置下载文件名称
  document.body.appendChild(aLink);
  aLink.click();
  URL.revokeObjectURL(aLink.href); //清除引用
  document.body.removeChild(aLink);
}

/**
 * @description: 获取所有views下的 .vue 文件信息
 * 多层级文件动态导入。 /home/index
 * 注： vite  默认只支持一级文件
 */
const modules = import.meta.glob("../views/**/*.vue");
// console.log(modules, "获取所有的路径");

/**
 * @description: 树形转路由
 */
export function handleRouter(routers) {
  const newRoutes = routers.map((r) => {
    const route = {
      path: r.path,
      meta: {
        title: r.title,
        icon: r.icon,
      },
      redirect: r.redirect,
      name: r.name,
      component: modules[`../views${r.component}.vue`],
    };
    // 重定向
    if (r.redirect) {
      route.redirect = r.redirect;
    }
    if (r.children) {
      route.children = handleRouter(r.children);
    }
    return route;
  });
  return newRoutes;
}

/**
 * @description: 数组转树形，并且排序
 * @return {*}
 */

export function toTree({
  arrList = [],
  id = "id",
  pid = "pid",
  order = "sort",
}) {
  let up = arrList
    .filter((x) => x[pid] === null)
    .sort((a, b) => a[order] - b[order]);
  let cp = arrList.filter((x) => x[pid]);
  getData(up);
  function getData(arr = []) {
    arr.forEach((element) => {
      let ar = cp
        .filter((item) => element[id] == item[pid])
        .sort((a, b) => a[order] - b[order]);
      if (ar.length) {
        element.children = ar;
        element.redirect = ar[0].path;
      }
      if (ar.length < cp.length) {
        getData(element.children);
      }
    });
  }
  return up;
}
